package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.AdminLoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-04-24 08:22:32
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper userMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public R adminLogin(AdminLoginVo adminLoginVo) {
        //获取用户信息
        TbUser tbUser = userMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, adminLoginVo.getUserName()));
        if(tbUser==null){
            return R.ERROR(404,"用户不存在");
        }
        //校验密码
        if(!adminLoginVo.getUserPass().equals(tbUser.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName",tbUser.getUserName())
                .claim("userPass",tbUser.getUserPass())
                .claim("userMobile",tbUser.getUserMobile())
                .claim("userEmail",tbUser.getUserEmail())
                .compact();
        //缓存token
        String redisKey="token-"+tbUser.getUserId();
        redisTemplate.opsForValue().set(redisKey,token,15, TimeUnit.MINUTES);
        //返回对象
        tbUser.setToken(token);
        tbUser.setUserPass(null);
        return R.OK(tbUser);
    }


}




